package com.winit.openapi.apiadapter.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.oms.spi.outbound.OutboundOrderService;
import com.winit.oms.spi.outbound.command.order.QueryOrderBySellerCommand;
import com.winit.oms.spi.outbound.vo.OutboundOrderEnumContants;
import com.winit.oms.spi.outbound.vo.OutboundOrderVo;
import com.winit.openapi.apiadapter.controller.builder.OrderAdapteBuilder;
import com.winit.openapi.apiadapter.controller.validator.OrderAdapteValidator;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.ups.spi.sys.CustomerTansferConfigService;

/**
 * 3E查询出库单列表信息Controller适配. 1.该接口对来自卖家网站的请求，直接转发至3E，不做适配
 * 2.对于非卖家网站的请求，会根据入参判断到底是要调3E还是OMS，如果无法判断，就两边都调用，合并结果返回
 * 
 * @version <pre>
 * Author   Version     Date        Changes
 * minghao.deng     1.0         2016年12月22日     Created
 *
 * </pre>
 * @since 1.
 */
@Controller
public class QueryOrderListAdapteController extends BaseController {

    private static final Logger          logger = LoggerFactory.getLogger(QueryOrderListAdapteController.class);

    @Resource
    private CustomerTansferConfigService customerTansferConfigService;

    @Resource
    private OutboundOrderService         outboundOrderService;

    @Resource
    private OrderAdapteBuilder           orderAdapteBuilder;

    @RequestMapping(value = "/queryOutboundOrderList")
    public String queryOutboundOrderList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        if (null == json) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        OrderAdapteValidator.validateQueryOrderListPara(json);
        JSONObject outPutJson = new JSONObject();
        outPutJson.put("currentPageNum", 1);
        outPutJson.put("currentPageSize", 200);
        outPutJson.put("total", 0);
        outPutJson.put("list", new ArrayList<Object>());
        responseMsg.setData(outPutJson);
        ValidateUtil.validNotNull(json, "dateOrderedStartDate");
        ValidateUtil.validNotNull(json, "dateOrderedEndDate");

        queryOrderFromOpenAPI(requestMsg, responseMsg);


        return API_ADAPTED_SUCCESS;
    }

    private int queryOrderFromOpenAPI(RequestMsg requestMsg, ResponseMsg responseMsg) {
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());

        List<Map<String, Object>> datalist = new ArrayList<Map<String, Object>>();
        JSONObject result = orderAdapteBuilder.buildPagePara(requestMsg, responseMsg);
        responseMsg.setData(result);
        Page<OutboundOrderVo> pagelist = getNewOrderList(json);

        if (null != pagelist) {
            datalist = buildOrderList(pagelist.getContent());
            result.put("list", datalist);
            result.put("total", pagelist.getTotalElements());

            return (int) pagelist.getTotalElements();

        }
        return 0;

    }

    private Page<OutboundOrderVo> getNewOrderList(JSONObject json) {
        Page<OutboundOrderVo> pagelist = null;
        try {
            QueryOrderBySellerCommand command = new QueryOrderBySellerCommand();
            OrderAdapteValidator.validInputPara(json);
            command = orderAdapteBuilder.buildQueryOutboundCommand(json);
            Searchable searchable = buildSearchablePageParams(json);
            if (OutboundOrderEnumContants.OrderStatus.DR.getStatus().equals(json.getString("status"))) {
                searchable.addSort(new Sort(Direction.DESC, "CREATED"));
            } else {
                searchable.addSort(new Sort(Direction.DESC, "ORDER_TIME"));
            }
            command.setSearchable(searchable);
            pagelist = outboundOrderService.getOrderListBySeller(command);
        } catch (Exception e) {
            logger.error("查询出库单列表失败。");
        }
        return pagelist;
    }

    private List<Map<String, Object>> buildOrderList(List<OutboundOrderVo> datalist) {
        List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
        try {
            for (OutboundOrderVo order : datalist) {
                Map<String, Object> map = orderAdapteBuilder.buildOutboundOrderListAdaptePageVo(order);
                resultList.add(map);
            }
        } catch (Exception e) {
            logger.warn("查询出库单列表，构建信息失败");
        }
        return resultList;
    }

    public Searchable buildSearchablePageParams(JSONObject json) {
        int pageNo = ApiConstant.PAGE_NO_DEFAULT;
        int pageSize = ApiConstant.PAGE_SIZE_DEFAULT;
        if (ValidateUtil.isIntNumber(json.getString("pageNum"))) {
            pageNo = json.getInteger("pageNum");
            if (pageNo <= 0) {
                throw new ApiException(ErrorCode.FIELD_ERROR, "pageNum");
            }
        } else if (isExistValue(json, "pageNum") && !ValidateUtil.isIntNumber(json.getString("pageNum"))) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageNum");
        }

        if (ValidateUtil.isIntNumber(json.getString("pageSize"))) {
            pageSize = json.getInteger("pageSize");
            if (pageSize <= 0) {
                throw new ApiException(ErrorCode.FIELD_ERROR, "pageSize");
            }
        } else if (isExistValue(json, "pageSize") && !ValidateUtil.isIntNumber(json.getString("pageSize"))) {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "pageSize");
        }

        Searchable search = Searchable.newSearchable();
        search.setPage(pageNo, pageSize);
        return search;
    }

}
